﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Observable;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Collections.Specialized;

namespace SpeakupBackend.Themes
{
    [Serializable]
    public class ClubThemeCollection : ObservableCollectionBase<ClubTheme, HashSet<ClubTheme>>
    {
        public ClubThemeCollection() :
            base(new HashSet<ClubTheme>())
        {
        }

        void Merge(ClubThemeCollection other)
        {
            using (var transaction = BeginTransaction())
            {
                foreach (var theirsItem in other.InternalCollection)
                {
                    if (InternalCollection.Add(theirsItem))
                    {
                        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, theirsItem));
                    }                    
                }
            }
        }


        #region Binary serialization

        public void Save(String fileName)
        {
            BinaryFormatter formatter = new BinaryFormatter();
            using (FileStream fileStream = new FileStream(fileName, FileMode.Create))
            {
                formatter.Serialize(fileStream, this);
            }            
        }

        public static ClubThemeCollection Load(String fileName)
        {
            BinaryFormatter formatter = new BinaryFormatter();
            using (FileStream fileStream = new FileStream(fileName, FileMode.Open))
            {
                return (ClubThemeCollection)formatter.Deserialize(fileStream);
            }
        }

        public void ReloadFrom(String fileName)
        {
            Clear();

            ClubThemeCollection otherCollection = Load(fileName);
            Merge(otherCollection);
        }

        #endregion
    }
}
